//
//  TFUITabView.m
//  TFFoundation
//
//  Created by 夏之祥 on 2019/4/26.
//

#import "TFUITabView.h"
#import <Masonry/Masonry.h>
#import "TFUIDefine.h"

@implementation TFUITabIndicatorView

- (instancetype)initWithStyle:(TFUITabIndicatorViewStyle)style {
    self = [super init];
    if (self) {
        self.style = style;
    }
    return self;
}

@end


@interface TFUITabView ()<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property(nonatomic, strong, readwrite) UICollectionView *collectionView;

@property(nonatomic, assign, readwrite) NSInteger tabIndex;

@end

@implementation TFUITabView

- (instancetype)initWithDataSourceArray:(NSArray *)dataSourceArray {
    self = [super init];
    if (self) {
        self.dataSourceArray = dataSourceArray;
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self didInitialize];
        [self addSubview:self.collectionView];
        [self.collectionView addSubview:self.indicatorView];
        [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(UIEdgeInsetsZero);
        }];
    }
    return self;
}

- (void)didInitialize {
    self.tabIndex = 0;
    [self.collectionView registerClass:[self cellClass] forCellWithReuseIdentifier:NSStringFromClass([self cellClass])];
}

- (Class)cellClass {
    return [UICollectionViewCell class];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    if (CGRectGetWidth(_collectionView.frame)&&!self.collectionView.indexPathsForSelectedItems.count) {
        [self.collectionView selectItemAtIndexPath:[NSIndexPath indexPathForRow:self.tabIndex inSection:0] animated:YES scrollPosition:UICollectionViewScrollPositionNone];
    }
}

- (void)associatedScrollViewDidScroll:(UIScrollView *)associatedScrollView {
    [self associatedScrollView:associatedScrollView contentOffsetDidChange:associatedScrollView.contentOffset];
}

- (void)associatedScrollView:(UIScrollView *)associatedScrollView contentOffsetDidChange:(CGPoint)contentOffset {
    if (associatedScrollView.isDragging) {
        CGFloat ratio = contentOffset.x/CGRectGetWidth(associatedScrollView.bounds);
        if (ratio > self.dataSourceArray.count - 1 || ratio < 0) {
            //超过了边界，不需要处理
            return;
        }
        ratio = MAX(0, MIN(self.dataSourceArray.count - 1, ratio));
        NSInteger baseIndex = floorf(ratio);
        if (baseIndex + 1 >= self.dataSourceArray.count) {
            //右边越界了，不需要处理
            return;
        }
        CGFloat remainderRatio = ratio - baseIndex;
        UICollectionViewCell *currentCell = [self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:baseIndex inSection:0]];
        UICollectionViewCell *nextCell = [self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:baseIndex+1 inSection:0]];
        [self transitionWithCurrentCell:currentCell currentCellIndex:baseIndex nextCell:nextCell nextCellIndex:baseIndex+1 percent:remainderRatio];
    }
}

- (void)transitionWithCurrentCell:(__kindof UICollectionViewCell *)currentCell currentCellIndex:(NSInteger)currentCellIndex nextCell:(__kindof UICollectionViewCell *)nextCell nextCellIndex:(NSInteger)nextCellIndex percent:(float)percent {
    CGRect currentCellFrame = currentCell.frame;
    CGRect nextCellFrame = nextCell.frame;
    CGRect leftIndicatorViewFrame = [self indicatorViewFrameInCurrentStyleWithCellFrame:currentCellFrame cellIndex:currentCellIndex];
    CGRect rightIndicatorViewFrame = [self indicatorViewFrameInCurrentStyleWithCellFrame:nextCellFrame cellIndex:nextCellIndex];
    CGRect indicatorViewFrame = leftIndicatorViewFrame;
    indicatorViewFrame.size.width = CGRectGetWidth(leftIndicatorViewFrame) + percent * (CGRectGetWidth(rightIndicatorViewFrame) - CGRectGetWidth(leftIndicatorViewFrame));
    indicatorViewFrame.origin.x = CGRectGetMinX(leftIndicatorViewFrame) + percent * (CGRectGetMinX(rightIndicatorViewFrame) - CGRectGetMinX(leftIndicatorViewFrame));
    [self updateIndicatorViewWithTargetFrame:indicatorViewFrame animated:NO];
}


- (CGRect)indicatorViewFrameInCurrentStyleWithCellFrame:(CGRect)cellFrame cellIndex:(NSInteger)cellIndex {
    switch (self.indicatorView.style) {
        case TFUITabIndicatorViewStyleLine:{
            return UIEdgeInsetsInsetRect(cellFrame, UIEdgeInsetsMake(cellFrame.size.height-2.0, 0.0, 0.0, 0.0));
        }
            break;
        case TFUITabIndicatorViewStyleOval:{
            return UIEdgeInsetsInsetRect(cellFrame, UIEdgeInsetsMake(4.0, -10.0, 4.0, -10.0));
        }
            break;
        case TFUITabIndicatorViewStyleCustom: {
            return CGRectZero;
        }
            break;
        default:
            break;
    }
}

- (void)updateIndicatorViewWithTargetFrame:(CGRect)targetFrame animated:(BOOL)animated {
    if (self.indicatorView.style==TFUITabIndicatorViewStyleOval) {
        self.indicatorView.layer.cornerRadius = CGRectGetHeight(targetFrame)*0.5;
        self.indicatorView.layer.masksToBounds = YES;
    }
    if (animated) {
        [UIView animateWithDuration:0.3 animations:^{
            self.indicatorView.frame = targetFrame;
        }];
    }
    else {
        self.indicatorView.frame = targetFrame;
    }
}

- (void)selectTabAtIndex:(NSInteger)index animated:(BOOL)animated {
    self.tabIndex = index;
    if ([self.delegate respondsToSelector:@selector(tabView:didSelectTabAtIndex:animated:)]) {
        [self.delegate tabView:self didSelectTabAtIndex:index animated:animated];
    }
    if (self.didSelectTabBlock) {
        self.didSelectTabBlock(self, index, animated);
    }
    if (!([self.collectionView.indexPathsForSelectedItems lastObject].row!=index&&self.collectionView.indexPathsForSelectedItems.count)) {
        [self.collectionView selectItemAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] animated:NO scrollPosition:UICollectionViewScrollPositionCenteredHorizontally];
    }

    CGRect cellFrame = [self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]].frame;
    CGRect indicatorViewFrame = [self indicatorViewFrameInCurrentStyleWithCellFrame:cellFrame cellIndex:index];
    [self updateIndicatorViewWithTargetFrame:indicatorViewFrame animated:animated];
}

#pragma mark - UICollectionViewDataSource,UICollectionViewDelegateFlowLayout

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataSourceArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([self cellClass]) forIndexPath:indexPath];
    [self updateCell:cell atIndex:indexPath.row];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [self didSelectCell:[collectionView cellForItemAtIndexPath:indexPath] atIndex:indexPath.row];
    [self selectTabAtIndex:indexPath.row animated:YES];
}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
    [self didDeselectCell:[collectionView cellForItemAtIndexPath:indexPath] atIndex:indexPath.row];
}

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    [self.collectionView sendSubviewToBack:self.indicatorView];
    if (indexPath.row==self.tabIndex&&(CGRectGetWidth(self.indicatorView.frame)<=0||CGRectGetMinX(self.indicatorView.frame)<=0||CGRectGetMinY(self.indicatorView.frame)<=0)) {
        [self selectTabAtIndex:indexPath.row animated:NO];
        [self updateIndicatorViewWithTargetFrame:[self indicatorViewFrameInCurrentStyleWithCellFrame:cell.frame cellIndex:indexPath.row] animated:NO];
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return [self cellSizeAtIndex:indexPath.row];
}

- (void)updateCell:(__kindof UICollectionViewCell *)cell atIndex:(NSInteger)index {
    
}

- (void)didSelectCell:(__kindof UICollectionViewCell *)cell atIndex:(NSInteger)index {
    
}

- (void)didDeselectCell:(__kindof UICollectionViewCell *)cell atIndex:(NSInteger)index {
    
}

- (CGSize)cellSizeAtIndex:(NSInteger)index {
    return CGSizeZero;
}


#pragma mark - lazy load.

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        _collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:flowLayout];
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsHorizontalScrollIndicator = NO;
    }
    return _collectionView;
}

- (TFUITabIndicatorView *)indicatorView {
    if (!_indicatorView) {
        _indicatorView = [[TFUITabIndicatorView alloc] initWithStyle:TFUITabIndicatorViewStyleLine];
    }
    return _indicatorView;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end



@interface TFUITextCollectionViewCell : UICollectionViewCell

@property (nonatomic, strong) UILabel *textLabel;

@end


@implementation TFUITextCollectionViewCell

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self.contentView addSubview:self.textLabel];
        [_textLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(UIEdgeInsetsZero);
        }];
    }
    return self;
}

#pragma mark - lazy load.

- (UILabel *)textLabel {
    if (!_textLabel) {
        _textLabel = [[UILabel alloc] init];
        _textLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _textLabel;
}

@end

@interface TFUITextTabView ()

@property(nonatomic, strong) NSArray *textWidthArray;

@property(nonatomic, assign) CGFloat textTotalWidth;

@end

@implementation TFUITextTabView

- (void)didInitialize {
    [super didInitialize];
    self.textFont = [UIFont systemFontOfSize:14];
    self.textColor = [UIColor blackColor];
    self.textSelectedFont = [UIFont systemFontOfSize:14];
    self.textSelectedColor = [UIColor blueColor];
    self.textMinSpacing = 10.0;
    self.textLeftInset = 10.0;
    self.textRightInset = 10.0;
    self.indicatorView.backgroundColor = self.textSelectedColor;
}

- (Class)cellClass {
    return [TFUITextCollectionViewCell class];
}

- (void)setDataSourceArray:(NSArray *)dataSourceArray{
    [super setDataSourceArray:dataSourceArray];
    [self p_reLayout];
}

- (void)setTextFont:(UIFont *)textFont {
    _textFont = textFont;
    [self p_reLayout];
}

- (void)setTextSelectedFont:(UIFont *)textSelectedFont {
    _textSelectedFont = textSelectedFont;
    [self p_reLayout];
}

- (void)setTextLeftInset:(CGFloat)textLeftInset {
    _textLeftInset = textLeftInset;
    [self p_reLayout];
}

- (void)setTextRightInset:(CGFloat)textRightInset {
    _textRightInset = textRightInset;
    [self p_reLayout];
}

- (void)setTextMinSpacing:(CGFloat)textMinSpacing {
    textMinSpacing = textMinSpacing;
    [self p_reLayout];
}


- (void)p_reLayout {
    if (self.dataSourceArray.count) {
        _textTotalWidth = 0.0;
        NSMutableArray *textWidthArray = @[].mutableCopy;
        for (NSString *text in self.dataSourceArray) {
            CGFloat textWidth = ceilf(MAX([text sizeWithAttributes:@{NSFontAttributeName:self.textFont}].width, [text sizeWithAttributes:@{NSFontAttributeName:self.textSelectedFont}].width));
            [textWidthArray addObject:@(textWidth)];
            _textTotalWidth += textWidth;
        }
        _textWidthArray = [NSArray arrayWithArray:textWidthArray];
        UICollectionViewFlowLayout *flowLayout = self.collectionView.collectionViewLayout;
        flowLayout.minimumInteritemSpacing = self.textMinSpacing;
        flowLayout.minimumLineSpacing = self.textMinSpacing;
        flowLayout.sectionInset = UIEdgeInsetsMake(0.0, self.textLeftInset, 0.0, self.textRightInset);
        [self p_layoutCenter];
        [self.collectionView reloadData];
    }
}

- (void)layoutSubviews {
    [super layoutSubviews];
    [self p_layoutCenter];
}

- (void)p_layoutCenter {
    //自动居中
    CGFloat collectionViewWidth = CGRectGetWidth(self.collectionView.frame);
    if (collectionViewWidth&&(collectionViewWidth>(_textTotalWidth+(self.dataSourceArray.count-1)*self.textMinSpacing)+self.textLeftInset+self.textRightInset)) {
        CGFloat space = floorf((collectionViewWidth-_textTotalWidth)/(_textWidthArray.count+1));
        UICollectionViewFlowLayout *flowLayout = self.collectionView.collectionViewLayout;
        flowLayout.minimumInteritemSpacing = space;
        flowLayout.minimumLineSpacing = space;
        flowLayout.sectionInset = UIEdgeInsetsMake(0.0, space, 0.0, space);
    }
}

- (void)transitionWithCurrentCell:(TFUITextCollectionViewCell *)currentCell currentCellIndex:(NSInteger)currentCellIndex nextCell:(TFUITextCollectionViewCell *)nextCell nextCellIndex:(NSInteger)nextCellIndex percent:(float)percent {
    [super transitionWithCurrentCell:currentCell currentCellIndex:currentCellIndex nextCell:nextCell nextCellIndex:nextCellIndex percent:percent];
    currentCell.textLabel.textColor = TFUIInterpolationColor(self.textSelectedColor, self.textColor, percent);
    nextCell.textLabel.textColor = TFUIInterpolationColor(self.textColor, self.textSelectedColor, percent);
}

- (void)updateCell:(TFUITextCollectionViewCell *)cell atIndex:(NSInteger)index {
    cell.textLabel.text = self.dataSourceArray[index];
    if (self.tabIndex==index) {
        [self didSelectCell:cell atIndex:index];
    }
    else {
        [self didDeselectCell:cell atIndex:index];
    }
}

- (CGSize)cellSizeAtIndex:(NSInteger)index {
    return CGSizeMake([_textWidthArray[index] floatValue], CGRectGetHeight(self.collectionView.frame));
}

- (void)didSelectCell:(TFUITextCollectionViewCell*)cell atIndex:(NSInteger)index {
    cell.textLabel.font = self.textSelectedFont;
    cell.textLabel.textColor = self.textSelectedColor;
}

- (void)didDeselectCell:(TFUITextCollectionViewCell*)cell atIndex:(NSInteger)index {
    cell.textLabel.font = self.textFont;
    cell.textLabel.textColor = self.textColor;
}


@end



